package com.sw.servlet.util;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author sw
 * @project minicat
 * @description
 * @date 2020/4/29 22:27
 */
public class StaticResourceUtil {
    /**
     * 获取静态资源绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath=StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replace("\\\\","/")+path;
    }

    /**
     * 静态资源写出
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResources(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count=0;
        while (count==0){
            count=fileInputStream.available();
        }
        int resourceSize=count;
        //输出http请求头和内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        //读取内容
        long written=0;
        int byteSize=1024;//每次读取长度

        byte[] bytes=new byte[byteSize];
        while (written<resourceSize){
            if(written+byteSize>resourceSize){//已经写的+剩余的 剩余的文件长度 不足1024
                byteSize= (int) (resourceSize-written);//
                bytes=new byte[byteSize];
            }
            fileInputStream.read(bytes);
            outputStream.write(bytes);
            written+=byteSize;
        }
    }
}
